package com.bd.cp.service.upc.exectuor;

import org.springframework.context.Lifecycle;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

@Component
public class UpcExecutor implements Lifecycle {

    private ThreadPoolTaskExecutor executor;

    @Bean("upcExecutor")
    public ThreadPoolTaskExecutor threadPoolExecutor() {
        int coreTasks = Runtime.getRuntime().availableProcessors() * 2;
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coreTasks);
        executor.setMaxPoolSize(coreTasks);
        executor.setKeepAliveSeconds(3);
        //底层使用SynchronousQueue
        executor.setQueueCapacity(-1);
        executor.setThreadNamePrefix("upc-import");
        //回调方式，不允许任务丢弃
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        //销毁时等待5秒
        executor.setAwaitTerminationSeconds(5);
        executor.setWaitForTasksToCompleteOnShutdown(true);

        this.executor = executor;
        return executor;
    }


    @Override
    public void start() {

    }

    /**
     * AbstractApplicationContext.doClose中被作为lifeBean销毁
     */
    @Override
    public void stop() {
        //直接调用destroy方法进行销毁
        this.executor.destroy();
    }

    @Override
    public boolean isRunning() {
        return false;
    }
}
